package com.huas.handler;

import com.alibaba.fastjson.JSONObject;
import com.huas.common.Result;
import com.huas.constant.MessageConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权异常处理
 */
@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.info("用户权限不足");
        Result<Object> result = Result.error(MessageConstant.ACCOUNT_ROLE_LACK);
        String json = JSONObject.toJSONString(result);
        //处理中文显示问号?
        response.setContentType("text/html;charset=utf-8");
        //设置状态码403forbidden，与前端对应
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().write(json);
    }
}
